package com.tanhua.mongo.api;

import com.tanhua.api.UserLikeApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存喜欢/不喜欢数据
    @Override
    public boolean save(Long userId, Long likeUserId, boolean isLike) {
        try {
            //封装查询条件
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));

            //判断数据是否存在
            if (mongoTemplate.exists(query, UserLike.class)) {
                //存在 修改
                Update update = Update.update("isLike", isLike);
                mongoTemplate.updateFirst(query, update, UserLike.class);
            } else {
                //不存在 新增
                UserLike userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setIsLike(isLike);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());

                mongoTemplate.save(userLike);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     * 请求参数：
     * userId 当前登录用户id
     * 响应结果：
     * eachLoveCount  互相喜欢（查询Friend）  loveCount 喜欢  fanCount 粉丝 Integer 类型
     * 可以使用Map 集合来封装
     */
    @Override
    public Map<String,Integer> counts(Long userId) {

        Integer eachLoveCount = 0;

        Integer loveCount = 0;

        List<Long> friendIds = new ArrayList<>();

        //1.统计互相喜欢
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        /*获取相互喜欢列表*/
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        if(friends != null){
            eachLoveCount = friends.size();
            // 获取互相喜欢的朋友id
            friendIds = friends.stream().map(s -> s.getFriendId()).collect(Collectors.toList());
        }


        //2.统计我喜欢

        /*获取我喜欢的用户列表*/
        criteria.and("isLike").is(true);
        List<UserLike> userLikes = mongoTemplate.find(new Query(criteria), UserLike.class);
        /*获取喜欢列表数据*/
        List<Long> collect1 = new ArrayList<>();
        if(userLikes != null){
            collect1 = userLikes.stream().map(s -> s.getLikeUserId()).collect(Collectors.toList());
        }
        List<Long> onlyLike = new ArrayList<>();
        for (Long aLong : collect1) {
            if(!friends.contains(aLong)){
                onlyLike.add(aLong);
            }
        }
        loveCount = onlyLike.size();


        //3.统计粉丝（喜欢我）
        Criteria criteria1 = Criteria.where("likeUserId").is(userId).and("isLike").is(true);
        Query query1 = Query.query(criteria1);
//        long fanCount = mongoTemplate.count(query1, UserLike.class);
        List<UserLike> userLikes1 = mongoTemplate.find(query1, UserLike.class); //查询当前被喜欢的列表
        List<Long> collect = new ArrayList<>();
        List<Long> newCollect = new ArrayList<>();
        if(userLikes1 != null){
            collect = userLikes1.stream().map(s -> s.getUserId()).collect(Collectors.toList());  //获取所有粉丝id
        }
        for (Long aLong : collect) {
            if(!friendIds.contains(aLong)){
                newCollect.add(aLong);
            }
        }



        Integer fanCount = newCollect.size();

        //4.封装数据
        Map<String,Integer> map =new HashMap<>();
        map.put("eachLoveCount", Math.toIntExact(eachLoveCount));
        map.put("loveCount", Math.toIntExact(loveCount));
        map.put("fanCount", Math.toIntExact(fanCount));

        //5.返回数据
        return map;
    }

    //判断双方是否为互相喜欢
    @Override
    public Boolean exists(Long userId, Long likeUserId) {
        //1.判断我是否喜欢用户
        Criteria criteria = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLike.class);

        //2.判断用户是否喜欢我
        Criteria criteria1 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);
        Query query1 = Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, UserLike.class);

        //3.返回值
        if (exists && exists1) {
            return true;
        } else {
            return false;
        }
    }


    //分页查询喜欢表
    @Override
    public List<UserLike> findByPage(Integer type, Integer page, Integer pagesize, Long userId) {
        Criteria criteria = new Criteria();
        if (type == 2) {
            criteria = Criteria.where("userId").is(userId).and("isLike").is(true);
        } else {
            criteria = Criteria.where("likeUserId").is(userId).and("isLike").is(true);
        }
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        return userLikeList;
    }


    //保存用户喜欢
    @Override
    public void saveLove(UserLike userLike) {
        //1.判断用户喜欢我 在数据库是否有数据
        Criteria criteria = Criteria.where("userId").is(userLike.getLikeUserId()).and("likeUserId").is(userLike.getUserId());
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLike.class);

        //2.修改用户喜欢我的isLike字段  false 修改为 true
        if (exists) {
            Update update = new Update();
            update.set("isLike", true);
            mongoTemplate.updateFirst(query, update, UserLike.class);
        }

        //3.判断我喜欢用户在数据库是否有数据
        Criteria criteria1 = Criteria.where("userId").is(userLike.getUserId()).and("likeUserId").is(userLike.getLikeUserId());
        Query query1 = Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, UserLike.class);
        //4.添加数据
        if (!exists1) {
            mongoTemplate.save(userLike);
        }
    }


    //数据库删除此条数据
    @Override
    public void deleteLove(Long userId, Long likeUserId) {
        //1.数据库删除此条数据
        Criteria criteria = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, UserLike.class);

        //2.判断用户是否喜欢我
        Criteria criteria1 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);
        Query query1 = Query.query(criteria);
        boolean exists1 = mongoTemplate.exists(query1, UserLike.class);

        //3.如果是 则把isLike 字段 修改为 false
        if (exists1) {
            Update update = new Update();
            update.set("isLike", true);
            mongoTemplate.updateFirst(query, update, UserLike.class);
        }
    }


}
